<template>
  <div>
    <el-form ref="ruleForm" label-position="right" size="small" label-width="110px" class="base-search-more">
       <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="所属区域">
            <el-select style="width:100%" v-model="form.agentId" filterable default-first-option
                       placeholder="--区域--" @change="getRoleList">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户名称">
            <el-input style="width: 100%" placeholder="搜索用户名称" v-model="params.realname" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户手机号">
            <el-input style="width: 100%" placeholder="搜索手机号" v-model="params.mobile" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属部门">
            <el-select style="width:100%" v-model="params.rid" filterable default-first-option placeholder="--区域--" clearable>
              <el-option v-for="item in roleList" :key="item.rid" :label="item.rname"
                         :value="item.rid" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent ? 24 : 6" style="text-align: right;">
          <el-form-item label-width="0px">
            <el-button type="primary" icon="el-icon-search" @click="$refs.pagination.handleSizeChange(10)">查询</el-button>
            <el-button type="primary" plain icon="el-icon-plus" @click="handleClickEdit(1)">新增角色</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-table :data="tableData.list" stripe style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column prop="name" label="用户名" width="140" align="center"></el-table-column>
        <el-table-column prop="mobile" label="手机号" min-width="140" align="center"></el-table-column>
        <el-table-column prop="rname" label="所属部门" width="140" align="center"></el-table-column>
        <el-table-column label="修改时间" min-width="180" align="center">
          <template slot-scope="scope">
            {{scope.row.modifytime?scope.row.modifytime:scope.row.createtime}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="140" align="center">
          <template slot-scope="scope">
            <el-button class="el-text-check" @click="handleClickEdit(2,scope.row)" type="text" size="mini">编辑</el-button>
            <el-button @click="freezeUser(scope.row)" type="text" :style="{'color': scope.row.abnormal? '#8BC34A' : '#f56c6c'}" size="mini">{{scope.row.abnormal? '恢复': '冻结'}}</el-button>
            <el-button @click="deleteUser(scope.row)" type="text" style="color:red;" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pt-table-loading v-show="isloadingTable"></pt-table-loading>
      <pt-pagination ref="pagination" :total="tableData.total" @listeningEvent="triggerEvent"></pt-pagination>
    </div>

    <el-dialog :title="addOrEdit+'角色'" v-dialogDrag :visible.sync="dialogTableVisible" width="800px" height="500px"
               :close-on-press-escap="true">
      <el-form :model="form" ref="ruleForm" label-width="100px"  size="small">
        <el-form-item label="所属区域" prop="agentId"
                      :rules="[{ required: true, message: '请在列表页面上选择区域', trigger: 'change' }]">
          <el-row type="flex">
            <el-select v-model="form.agentId" :disabled="true">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-tooltip class="item" effect="dark" content="此处和列表页面同步,若想更改请在列表页面更改" placement="top-start">
              <el-button type="text" icon="el-icon-question"></el-button>
            </el-tooltip>
          </el-row>
        </el-form-item>

        <el-form-item label="名称" prop="realname" :rules="[{ required: true, message: '名称未填',trigger: 'blur' }]">
          <el-input v-model="form.realname" placeholder="输入部门的角色名称" />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile" :rules="[{required: true, message: '商家电话未填写' }]">
          <el-input type="number" v-model.number="form.mobile" placeholder="输入手机号" />
        </el-form-item>

        <el-form-item label="分配部门" prop="rid" :rules="[{required: true, message: '请选择部门', trigger: 'change' }]">
          <div class="right">
            <div class="head flex"><span class="st1">#</span><span class="st2">部门名称</span><span class="st3">描述</span>
            </div>
            <ul>
              <li class="flex-row" v-for="item in roleList" :key="item.rid">
                <el-radio v-model="form.rid" :label="item.rid">{{item.rname}}</el-radio>
                <span class="st4 text-over">{{item.info}}</span>
              </li>
            </ul>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isloadingUser" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import { frozenUser, deleteUser } from '@/api/agent'
  export default {
    data() {
      return {
        addOrEdit: '添加',//添加 修改文本提示
        isloadingUser: false, //保存用户
        isloadingTable: false, //表单等待
        editId: '', //被编辑用户的ID
        form: { //新增或修改角色
          realname: '',
          mobile: '',
          rid: '',
          agentId:''
        },
        roleList: [],//部门列表
        dialogTableVisible: false, //对话框
        typeSearch: '1', //控制搜索用户名称或手机号
        params: {//表格查询
          page: 0,
          size: 10,
          realname: '',
          mobile: '',
          rid:''
        },
        tableData: {} //表单数据
      }
    },
    computed: {
      restaurants() { // 区域数据
        return this.$store.state.agentListAll
      }
    },
    watch: {
      restaurants: {
        handler(val) {
          if (val && val.length) {
            if (val.length) { // 只有一个区域 直接显示
              this.form.agentId = val[0].id
              this.getRoleList(val[0].id)
            }
          }
        },
        deep: true
      }
    },
    methods: {
      handleClickEdit(type, row) { //打开对话框，开始新增
        if (type == 1) {
          this.addOrEdit = '添加'
          this.editId = ''
          this.form.realname = ''
          this.form.mobile = ''
          this.form.rid = ''
          this.dialogTableVisible = true
        } else if (type == 2) {
          this.addOrEdit = '修改'
          this.editId = row.id
          this.form.rid = row.byroles? parseInt(row.byroles): ''
          this.form.realname = row.name ? row.name.toString() : ''
          this.form.mobile = row.mobile ? row.mobile.toString() : ''
          this.dialogTableVisible = true
        }
      },
      getTableList() { //获取用户数据
        this.isloadingTable = true
        const params = { ...this.params }
        params.agentId = this.form.agentId
        this.$http.get('/server/user/list?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.tableData = res.data.data
          }
        }).finally(() => { this.isloadingTable = false })
      },
      getRoleList(id) { //获取所有部门
        const params = {agentId:id}
        this.roleList = []
        this.isloadingTable = true
        this.$http.get('/server/role/select?'+this.qs.stringify(params), {headers: {isCancel: true}}).then(res => {
          if (res.data.success) {
            this.roleList = res.data.data
            this.$refs.pagination.handleSizeChange(10)
          }
        }).finally(() => { this.isloadingTable = false })
      },
      submitForm(formName) { //新增和保存广告
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.form }
            this.isloadingUser = true
            if (this.editId) {
              params.id = this.editId
              this.$http.post('/server/user/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '修改用户成功！'})
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              }).finally(() => { this.isloadingUser = false })
            } else {
              this.$http.post('/server/user/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '新增用户成功！'})
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              }).finally(() => { this.isloadingUser = false })
            }
          } else {
            this.$message.error('有不合法或未填写的内容，请检查！')
            return false
          }
        })
      },
      freezeUser(row) { // 冻结人员
        const params = {id: row.id, frozen: !row.abnormal, reason: '' }
        frozenUser(params).then(res => {
          if (res.success) {
            this.$message.success('修改成功！')
            this.getTableList()
          }
        })
      },
      deleteUser(row) {
        this.$confirm(`是否删除人员,删除后无法恢复？`, '删除人员提示！', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'success',
          center: true
        }).then(() => {
          deleteUser({ id: row.id }).then(res => {
            if (res.success) {
              this.$message.success('删除成功！')
              this.getTableList()
            }
          })
        }).catch(() => {
          this.$message.info('已删除人员操作')
        })
      },
      tableRowClassName({row, rowIndex}) { // 表单样式
        if (row.abnormal) {
          return 'warning-freeze'
        }
        return ''
      },
      triggerEvent(type,val) { // 分页器
        if (type === 'page') {
          this.params.page = val - 1
        } else if (type === 'size') {
          this.params.page = 0
          this.params.size = val
        }
        this.getTableList()
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length) {
        this.form.agentId = this.restaurants[0].id
        this.getRoleList(this.restaurants[0].id)
      }
    }
  }

</script>
<style lang="scss" scoped>
  .right {
    flex: 1;
    border: 1px solid #e2e2e2;
  }

  .right .head {
    height: 30px;
    line-height: 30px;
    padding-left: 15px;
    background: #eff0f5;
    border-bottom: 1px solid #e2e2e2;
  }

  .right .head span {
    color: #01a0e1;
    font-weight: 600;
  }

  .right .head span.st1 {
    width: 20px;
  }

  .right .head span.st2 {
    width: 180px;
  }

  .right .head span.st3 {
    flex: 1;
  }

  .right ul {
    max-height: 380px;
    overflow-y: auto;
  }

  .right ul li {
    padding: 0 10px;
    height: 30px;
    line-height: 30px;
    border-bottom: 1px solid #e2e2e2;
  }

  .right ul li .el-radio {
    width: 200px;
    line-height: 30px;
  }

  .right ul li:last-child {
    border-bottom: none;
  }

  .right ul li .st4 {
    width: 450px;
    height: 30px;
    overflow: hidden;
    color: #909399;
  }
  /deep/ .warning-freeze td {
    color: #bcbcbc;
    font-weight: 600;
    .btn {
      color: #bcbcbc!important;
    }
    .border-red {
      border: 1px solid #bcbcbc !important;
    }
  }
</style>
